//代码得会自己写！！！！
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <poll.h>

int main(){

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);  //3

    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));

    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(8888);

    if(-1 == bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr))){
        perror("bind");
    }
    listen(sockfd, 10);


    // struct pollfd{
    //     int fd;
    //     short events;
    //     short revents;
    // };

    struct pollfd fds[1024];
    fds[sockfd].fd = sockfd;
    fds[sockfd].events = POLLIN;

    int maxfd = sockfd;
    while(1){
        for(int i=sockfd;i<=maxfd;i++){
            printf("before poll fds[%d].fd = %d, fds[%d].events = %d, fds[%d].revents = %d\n", i, fds[i].fd, i, fds[i].events, i, fds[i].revents);
        }
        printf("\n");
        int nready = poll(fds, maxfd+1, 1);    //timeout设置为-1
        for(int i=sockfd;i<=maxfd;i++){
            printf("after poll fds[%d].fd = %d, fds[%d].events = %d, fds[%d].revents = %d\n", i, fds[i].fd, i, fds[i].events, i, fds[i].revents);
        }

        if(fds[sockfd].revents & POLLIN){
            struct sockaddr_in client_addr;
            socklen_t client_addr_len = sizeof(client_addr);
            int connfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_addr_len);
            if(connfd > 0){
                fds[connfd].fd = connfd;
                fds[connfd].events = POLLIN;
                if(connfd > maxfd){
                    maxfd = connfd;
                }
            }
            fds[sockfd].revents = 0;
        }
        int i;
        for(i = sockfd + 1; i <= maxfd; i++){
            if(fds[i].revents & POLLIN){
                int connfd = fds[i].fd;
                char buf[1024];
                memset(buf, 0, sizeof(buf));
                int ret = recv(connfd, buf, sizeof(buf), 0);
                if(ret <= 0){
                    close(connfd);
                    //fds[i].fd = -1;
                }
                else{
                    printf("recv: %s\n", buf);
                }
                fds[i].revents = 0;
            }
        }
        printf("-------------------------------------------------\n");
        sleep(1);
    }

    getchar();
}